<template>
  <!-- <test-ee title="原生input">
    <div v-for="t in types" :key="t" style="width:100%">
      {{ t }}: <input :type="t" />
    </div>
  </test-ee> -->
  <ul>
    <li v-for="item, i1 in obj.Specs" :key="i1">
      <div>{{ item.CategoryName }}</div>
      <ee-space>
        <ee-tag v-for="child, i2 in item.Children" :key="i2" color="primary" :disabled="!canSelect.includes(child.SpecId)"
                :plain="!v.selected.includes(child.SpecId)"
                @click="v.selected.includes(child.SpecId) ? v.selected.remove(child.SpecId) : v.selected.push(child.SpecId)">
          {{ child.SpecName }}
        </ee-tag>
      </ee-space>
    </li>
  </ul>

  <form>
    <test-ee title="单选">
      值 {{ v.radio }}
      <ee-radio :options="optionsArr" disabled>不可用</ee-radio>
      <ee-radio type="button" disabled :options="optionsObjArr" v-model="v.radio">不可用</ee-radio>
      <ee-radio type="default" :options="optionsArr" v-model="v.radio">圈圈</ee-radio>
      <ee-radio type="tick" :options="optionsObj" v-model="v.radio">打勾</ee-radio>
      <ee-radio type="button" :options="optionsObjArr" v-model="v.radio">按钮</ee-radio>
    </test-ee>

    <test-ee title="多选">
      值 {{ v.checkbox }}
      <ee-checkbox :options="optionsArr" disabled>不可用</ee-checkbox>
      <ee-checkbox type="default" :options="optionsArr">圈圈</ee-checkbox>
      <ee-checkbox  v-model="v.testall" type="tick" :options="optionsObj">打勾</ee-checkbox>
      <ee-checkbox  v-model="v.testall" type="button" :options="optionsObjArr">按钮</ee-checkbox>
      <ee-checkbox-all v-model="v.testall" :options="optionsObj" :group="refs?.checkall"></ee-checkbox-all>
      <ee-checkbox type="button" :options="optionsObj" v-model="v.checkboxmin" min="2">限定最少2项</ee-checkbox>
      <ee-checkbox type="button" :options="optionsObj" v-model="v.checkboxmax" max="2">限定最多2选项</ee-checkbox>
      <ee-checkbox type="button" :options="optionsObj" v-model="v.checkboxminmax" min="2" max="3">限定2-3项</ee-checkbox>
      <ee-checkbox type="button" :options="optionsObj" v-model="v.checkboxfixed" min="2" max="2">限定固定2项</ee-checkbox>
      <ee-checkbox :options="optionsObj" @change="test" v-model="v.checkboxchange">
        change事件
        <ee-button @click="v.checkboxchange.push('v3', 'v4')">点击增加v3,v4</ee-button>
        <ee-button @click="v.checkboxchange = ['v1', 'v2']">点击变为v1,v2</ee-button>
      </ee-checkbox>
    </test-ee>

    <test-ee title="测试多选下拉框">
      <ee-selection placeholder="字符串数组" :options="optionsArr" ref="testRef"></ee-selection>
      <ee-selection placeholder="对象" :options="optionsObj"></ee-selection>
      <ee-selection placeholder="对象数组(不可选项)" :options="optionsObjArr"></ee-selection>
    </test-ee>

    <test-ee title="测试文本框">
      <ee-input placeholder="普通用法" />
      <input id="hidden" type="hidden" />
      <div contenteditable="">a</div>
      <a href="/">a href</a>
      <div style="width:100px;overflow:auto">
        <div tabindex="0" style="margin-left:150px;">abc</div>
      </div>
      <ee-input modelValue="只读" readonly @focus="test" @blur="test" />
      <ee-input placeholder="不可用" modelValue="不可用" disabled />
      <ee-input before="https://" after=".com" placeholder="输入框外前后有内容" />
      <ee-input iconLeft="search" iconRight="close" placeholder="输入框内前后有图标" />
      <ee-input left="https://" right=".com" placeholder="输入框内前后有文字" />
      <ee-input type="password" password placeholder="密码框" />
      <ee-input clear placeholder="带清除" />
      <ee-input limit maxlength="20" placeholder="统计字数" />
      <ee-input placeholder="什么都有" before="https://" after=".com" iconLeft="search" iconRight="setting" iconPassword clear
                limit maxlength="20" style="width: 100%;" />
      <ee-input ref="content" iconLeft="add" placeholder="内部有内容" @leftClick="optionsArr.push(optionsArr[0])"
                iconRight="close">
        <ul class="ee-select-options" v-show="refs.content?.focused">
          <ee-tag v-for="item, index in optionsArr" :key="item" closable class="primary plain" id="test"
                  @close="optionsArr.splice(index, 1)">
            {{ item }}
          </ee-tag>
        </ul>
      </ee-input>
    </test-ee>

    <test-ee title="测试开关">
      <ee-button @click="v.value1 = 100">修改 value 值为 100</ee-button>
      <ee-button @click="v.modelValue = 100">修改 modelValue 值为 100</ee-button>
      {{ v.modelValue }}
      <div>
        <ee-switch :value1="v.value1" v-model="v.modelValue" text0="关闭" text1="开启">
          <ee-svg-loading></ee-svg-loading>
        </ee-switch>
      </div>
    </test-ee>

    <test-ee title="测试单选下拉框">
      <pre>
        原生 select 可以是显示 1 个或多个选项。
        显示 1 个选项则是框架的 Select 组件的样子，但是无法输入内容，选项也只能是文字。
        选项很多时：
        1. PC 端下拉框的高度不会超出屏幕以可以看见所有项；
        2. PC 端显示在屏幕一半以下时，下拉框将向上展开，同样不会超出屏幕；
        3. MB 端暂未在真机测试，浏览器测试下拉框高度将会超出模拟器的区域；
        显示多个选项时则是下拉选项展开时的样子，有个滚动条。
        多选是通过 size 不为 1 并且按住 Ctrl + 点击来多选。
      </pre>
      <select id="mySelect">
        <option>Apple</option>
        <option>Pear</option>
        <option>Banana</option>
        <option>Orange</option>
      </select>
      <select id="mySelect" size="5" multiple>
        <template v-for="item in Array.from({ length: 100 })" :key="item">
          <option>Apple</option>
          <option>Pear</option>
          <option>Banana</option>
          <option>Orange</option>
        </template>
      </select>
      <ee-select placeholder="不可用" :options="optionsArr" disabled></ee-select>
      <ee-select placeholder="字符串数组" :options="optionsArr" ref="testRef"></ee-select>
      <ee-select placeholder="对象" :options="optionsObj"></ee-select>
      <ee-select placeholder="对象数组(不可选项)" :options="optionsObjArr"></ee-select>
      <ee-select placeholder="自定义字段" :options="optionsObjArr2" :mapper="optionsObjField"></ee-select>
      <ee-select placeholder="分组" :options="optionsGroup"></ee-select>
      <ee-select placeholder="键盘操作" first :options="optionsGroup"></ee-select>
      <ee-select placeholder="搜索" :options="optionsGroup" filter></ee-select>
      <ee-select placeholder="异步加载" filter :options="asyncOptions"></ee-select>
      <ee-select placeholder="异步搜索" :filter="{ search: asyncOptions, cache: 1 }"></ee-select>
      <ee-select placeholder="可清除" :options="optionsGroup" clear></ee-select>
      <ee-select placeholder="自定义选项模板" :options="optionsGroup">
        <template #item="{ item }">
          <span>{{ item.label }}</span>
          <div style="margin-left:auto;font-size:.875em;">{{ item.value }}</div>
        </template>
      </ee-select>
      <ee-select placeholder="无数据" :options="[]"></ee-select>
      <ee-select placeholder="(自定义值模板[单选可能不需要])" filter :options="optionsGroup">
        <template #value="{ item }">
          <span style="color:red"><ee-shape shape="close" />{{ item.label }}</span>
        </template>
      </ee-select>
      <ee-select placeholder="创建条目[搜索框默认]" create :options="optionsGroup"></ee-select>
      <ee-select placeholder="(级联)" :options="optionsGroup"></ee-select>
      <ee-select placeholder="(左右)" before="https://" after=".com" :options="optionsGroup"></ee-select>
      <ee-select placeholder="自定义下拉面板" :options="optionsArr">
        <ee-input ref="addOption" v-model="v.addOption" style="flex:1.5" placeholder="添加选项" />
        <ee-button style="flex-shrink:0" @click="v.addOption && optionsArr.push(v.addOption); v.addOption = null;">
          <ee-shape shape="add" />&nbsp;添加选项
        </ee-button>
      </ee-select>
    </test-ee>


  </form>

  <!-- <test-ee title="ee-form">
    <ee-form :form="form"></ee-form>
  </test-ee> -->

  <div id="io" class="eet visible">
    IntersectionObserver
  </div>

  <ee-empty></ee-empty>
</template>

<script type="text/javascript">
import refs from '@/ee-ui/__mixin/relation/refs';
import { form } from '../ee-ui/form/ee-form.vue'
import EeSelect from '@/ee-ui/form/ee-select.vue';
import { generateRandomStringArray } from './test';
import EeSvgLoading from '@/ee-ui/display/ee-svg-loading.vue';
import { ref, reactive, toRaw, isReactive } from 'vue';

export default {
  name: "test-ee-form",
  components: {
    EeSelect,
    EeSvgLoading
  },
  mixins: [refs],
  data() {
    return {
      obj: {
        "Id": "2d07fc0b-8fbc-4b68-a009-d9b64df7801e",
        "Name": "苹果",
        "Img": "http://img.scjiatianxia.com/13a7f049184a9ed885bf7e16b40e4eb0.jpg",
        "Price": 3,
        "OrgPrice": 5,
        "Absolutely": 1,
        "Recommend": 2,
        "MaxNum": 10,
        "SaleNumType": 2,
        "SaleNum": 5,
        "Count": 0,
        "StockStatus": 2,
        "Stock": 10,
        "Synopsis": "大大啊实打实",
        "HasSpec": 2,
        "CategoryId": "11177db5-085b-42ab-9a45-0cc5ed389d9a",
        "Specs": [
          {
            "CategoryId": "ae05a602-baaa-4f36-a7af-8fe618dae229",
            "CategoryName": "产地",
            "Children": [
              {
                "SpecId": "b1b6bf3c-3de8-40b7-a844-6d1d4d5325ba",
                "SpecName": "新疆",
                "IsChecked": false
              },
              {
                "SpecId": "3a7ca615-343a-4dca-b02e-c81fec701394",
                "SpecName": "四川",
                "IsChecked": false
              }
            ]
          },
          {
            "CategoryId": "e16b3391-f5c5-45bb-9c29-00f6b8e715ae",
            "CategoryName": "重量",
            "Children": [
              {
                "SpecId": "ca9fdc1d-4f8d-4e3a-ac1d-93cca1b326cb",
                "SpecName": "1kg",
                "IsChecked": false
              },
              {
                "SpecId": "4d51a576-d6d2-424a-8c68-edf0e592c569",
                "SpecName": "5kg",
                "IsChecked": false
              },
              {
                "SpecId": "408dc306-e6a7-4dab-8240-b75a51d7481b",
                "SpecName": "10kg",
                "IsChecked": false
              }
            ]
          },
          {
            "CategoryId": "cid",
            "CategoryName": "包装",
            "Children": [
              {
                "SpecId": "exquisite",
                "SpecName": "精致",
                "IsChecked": false
              },
              {
                "SpecId": "simple",
                "SpecName": "简单",
                "IsChecked": false
              },
            ]
          }
        ],
        "SpcePrices": [
          {
            "Id": "f44ac2a1-8918-4ae5-bea5-1d45b976071d",
            "Img": "http://img.scjiatianxia.com/13a7f049184a9ed885bf7e16b40e4eb0.jpg",
            "Price": 168,
            "OrgPrice": 190,
            "Count": 0,
            "TotalAmount": 0,
            "SpecIds": "3a7ca615-343a-4dca-b02e-c81fec701394,408dc306-e6a7-4dab-8240-b75a51d7481b,exquisite",
            "SpecNames": null
          },
          {
            "Id": "481e8a81-bbf6-4563-9a07-793f0967a5b3",
            "Img": "http://img.scjiatianxia.com/361696822e7a663a17383c2fb97b43f0.jpg",
            "Price": 90,
            "OrgPrice": 100,
            "Count": 0,
            "TotalAmount": 0,
            "SpecIds": "b1b6bf3c-3de8-40b7-a844-6d1d4d5325ba,4d51a576-d6d2-424a-8c68-edf0e592c569,simple",
            "SpecNames": null
          },
          {
            "Id": "825f1be4-079a-47f6-bc08-c94314d4a0ba",
            "Img": "http://img.scjiatianxia.com/8d611d0145ceefb453c776bb83414d41.jpg",
            "Price": 7,
            "OrgPrice": 10,
            "Count": 0,
            "TotalAmount": 0,
            "SpecIds": "3a7ca615-343a-4dca-b02e-c81fec701394,ca9fdc1d-4f8d-4e3a-ac1d-93cca1b326cb,simple",
            "SpecNames": null
          },
          {
            "Id": "3dd17afb-c261-473d-8885-d50cf0661dfb",
            "Img": "http://img.scjiatianxia.com/ac60a175be6da2c8ea5e424992f74230.jpg",
            "Price": 70,
            "OrgPrice": 80,
            "Count": 0,
            "TotalAmount": 0,
            "SpecIds": "3a7ca615-343a-4dca-b02e-c81fec701394,4d51a576-d6d2-424a-8c68-edf0e592c569,simple",
            "SpecNames": null
          },
          {
            "Id": "eeee0d15-6696-4fcc-a3fb-e69ea199dc67",
            "Img": "http://img.scjiatianxia.com/e6094e7fdea24171931b41988ef44fb1.jpg",
            "Price": 19,
            "OrgPrice": 20,
            "Count": 0,
            "TotalAmount": 0,
            "SpecIds": "b1b6bf3c-3de8-40b7-a844-6d1d4d5325ba,ca9fdc1d-4f8d-4e3a-ac1d-93cca1b326cb,simple",
            "SpecNames": null
          },
        ]
      },
      types: [
        "button",
        "checkbox",
        "color",
        "date",
        "datetime",
        "datetime-local",
        "email",
        "file",
        "hidden",
        "image",
        "month",
        "number",
        "password",
        "radio",
        "range",
        "reset",
        "search",
        "submit",
        "tel",
        "text",
        "time",
        "url",
        "week",
      ],

      optionsArr: [
        '选项1', '选项2', '选项3', '选项4',
      ],
      optionsObj: {
        v1: '选项1',
        v2: '选项2',
        v3: '选项3',
        v4: '选项4',
      },
      optionsObjArr: [
        { label: '选项1', value: 'v1', onChange: (item, value) => console.log("onChange", item, value), onChecked: (item, value) => console.log("onChecked", item, value) },
        { label: '选项2', value: 'v2' },
        { label: '选项3', value: 'v3' },
        { label: '选项4', value: 'v4', disabled: true },
      ],
      optionsObjArr2: [
        { tag: '选项1', v: 'v1' },
        { tag: '选项2', v: 'v2' },
        { tag: '选项3', v: 'v3' },
        { tag: '选项4', v: 'v4' },
      ],
      optionsObjField: {
        label: 'tag',
        value: 'v',
      },
      optionsGroup: [
        { label: '选项1', value: 'v1', group: '分类1' },
        { label: '选项25', value: 'v2' },
        { label: '选项3', value: 'v3', group: '分类2' },
        { label: '选项45', value: 'v4' },
      ],
      strings: generateRandomStringArray(200, 16),

      v: {
        selected: [],
      },

      /** @type {form} */
      form: {
        name: {
          label: '活动名称',
          type: 'text',
          rule: { required: true }
        },
        area: {
          label: '活动区域',
          type: 'select',
          props: {
            options: ['区域1', '区域2']
          },
          placeholder: '请选择活动区域',
          rule: { required: true }
        },
        time: [{
          label: '活动时间',
          placeholder: '选择日期',
          type: 'date',
          rule: { required: true }
        }, {
          label: '-'
        }, {
          placeholder: '选择时间',
          type: 'time',
        }],
        immediately: {
          label: '及时配送',
          type: 'boolean',
        },
        type: {
          label: '活动性质',
          type: 'checkbox',
          props: {
            options: ['美食/餐厅线上活动', '地推活动', '线下主题活动', '单纯品牌曝光']
          },
          rule: { required: true }
        },
        special: {
          label: '活动性质',
          type: 'radio',
          props: {
            options: ['线上品牌商赞助', '线下场地免费']
          },
          rule: { required: true }
        },
        special: {
          label: '活动形式',
          type: 'textarea',
          rule: { required: true }
        },
      },

      _computed: 0,
    }
  },
  props: {
  },
  computed: {
    /** 所有子分类的字典对象 { SpecId: 子分类对象 } */
    specs() {
      return this.obj.Specs.flatMap(i => i.Children).dic(i => i.SpecId);
    },
    /** 可以选择的子分类的 ID 数组 ["SpecId1", "SpecId2"] */
    canSelect() {
      const selected = this.v.selected;
      // 没有选中任何分类时默认全都可以选
      if (!selected.length)
        return Object.values(this.specs).filter(i => i.associated?.length > i.parent?.Children.length).map(i => i.SpecId);
      // 有选中分类时，其它可选分类应该是已经选中的分类的"关联分类"的交集
      let cross = undefined;
      selected.forEach(i => cross = this.specs[i].associated.filter(j =>
        this.specs[j].associated?.length > this.specs[j].parent?.Children.length &&
        (!cross || cross.includes(j))));
      return cross ?? [];
    }
  },
  methods: {
    test() {
      console.log("test", arguments)
    },
    asyncOptions(keyword, options) {
      console.log("获取异步选项", keyword, options)
      return new Promise(r => {
        setTimeout(() => {
          if (keyword) {
            const regex = new RegExp(keyword, "i");
            console.log("异步筛选结果", keyword, this.strings.filter(i => regex.test(i)))
            r(this.strings.filter(i => regex.test(i)));
          }
          else
            r(this.strings);
        }, 2000)
      })
    },
  },
  mounted() {
    // todo: IntersectionObserver 可以监视 DOM 元素进入视口，可用于首次进入的元素做出场动画
    // 在做滚动列表是否滚动到末尾时，可以使用此技巧来判断一个列表末尾的元素是否可见来刷新下一页的数据
    const io = new IntersectionObserver((entries) => {
      for (const entry of entries) {
        if (entry.isIntersecting) {
          entry.target.classList.add('eet-in-fade');
          entry.target.style.transitionDuration = '1s';
        } else {
          entry.target.classList.add('eet-in-fade');
        }
      }
    })
    document.querySelectorAll(".ee-select").forEach(i => io.observe(i))

    const obj = this.obj;
    obj.Specs.forEach(i => i.Children.forEach(j => {
      // 所有子分类 Parent 能方便拿到父分类
      j.parent = i;
      // 所有子分类里添加其它可选的子分类(包含本级的所有子分类)
      // 关联分类的数量仅为本级的所有子分类的数量时代表此分类缺货
      j.associated = i.Children.map(j => j.SpecId);
    }))
    // 将子分类扁平化并根据 ID 转换成字典方便获取
    const specs = this.specs;

    for (const item of obj.SpcePrices) {
      const split = item.SpecIds.split(',');
      // 冒泡排序的循环，子分类间两两循环到
      for (let i = 0; i < split.length; i++) {
        const spec1 = specs[split[i]];
        for (let j = i + 1; j < split.length; j++) {
          const spec2 = specs[split[j]];
          // 两个子分类，你中有我，我中有你
          spec1.associated.push(spec2.SpecId);
          spec2.associated.push(spec1.SpecId);
        }
      }
    }

    // 默认每个大分类选中第一个可选子分类
    for (const item of obj.Specs) {
      const can = this.canSelect;
      for (const spec of item.Children) {
        if (can.includes(spec.SpecId)) {
          this.v.selected.push(spec.SpecId);
          break;
        }
      }
    }


  },
}

</script>

<style lang="scss" scoped>
#test {
  font-size: 1em;
}
</style>